import { dialog, ipcMain } from 'electron';
import CodeController from '../controller/CodeController';
import ProcessService from '../service/ProcessService';
import log from 'electron-log/main';
import fs from 'fs/promises';
import { constants } from 'fs';

/**
 * 注册与代码相关的 IPC 事件处理器
 * 该函数会监听主进程与渲染进程之间的代码保存、获取、文件操作等事件
 */
export function setupCodeHandlers() {
  ipcMain.on('code:save', (event, code: string) => {
    CodeController.saveCode(event, code);
  });

  ipcMain.on('code:get', (event) => {
    CodeController.getCode(event);
  });

  ipcMain.on('code:save:file', (event, { code, filePath }) => {
    CodeController.saveCodeToFile(event, code, filePath);
  });

  ipcMain.on('code:dispose', (event) => {
    CodeController.dispose(event);
  });

  ipcMain.on('code:save:user-file', (event) => {
    CodeController.saveCodeToUserSelectedFile(event);
  });

  ipcMain.on('code:load:file', (event) => {
    CodeController.loadCodeFromFile(event);
  });

  ipcMain.handle('code:show-save-dialog', async () => {
    return await dialog.showSaveDialog({
      title: '选择保存路径',
      defaultPath: 'code.py',
      filters: [{ name: 'Python Files', extensions: ['py'] }],
    });
  });

  ipcMain.handle('code:select-folder', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
    });
    if (result.canceled) return null;
    return result.filePaths[0];
  });

  // ✅ 使用 fs.promises 和 fs.constants 异步判断文件夹是否存在并创建
  ipcMain.handle('code:create-folder', async (_event, folderPath: string) => {
    try {
      // 判断是否存在
      await fs.access(folderPath, constants.F_OK);
      // 存在
      return { success: false, message: 'Folder already exists.' };
    } catch {
      // 不存在则创建
      try {
        await fs.mkdir(folderPath, { recursive: true });
        return { success: true, message: 'Folder created.' };
      } catch (err) {
        return {
          success: false,
          message: `Error creating folder: ${(err as Error).message}`,
        };
      }
    }
  });

  // ✅ 简单封装：无论是否存在，都确保创建成功
  ipcMain.handle('code:ensure-folder', async (_event, folderPath: string) => {
    try {
      await fs.mkdir(folderPath, { recursive: true });
      return { success: true };
    } catch (error) {
      return { success: false, message: (error as Error).message };
    }
  });

  return () => {
    ipcMain.removeAllListeners('code:save');
    ipcMain.removeAllListeners('code:get');
    ipcMain.removeAllListeners('code:save:file');
    ipcMain.removeAllListeners('code:dispose');
    ipcMain.removeAllListeners('code:save:user-file');
    ipcMain.removeAllListeners('code:load:file');
    ipcMain.removeAllListeners('code:select-folder');
    ipcMain.removeAllListeners('code:create-folder');
    ipcMain.removeAllListeners('code:ensure-folder');
  };
}
